package com.wxg.toolkit.tray;

import java.awt.AWTException;
import java.awt.Image;
import java.awt.MenuItem;
import java.awt.PopupMenu;
import java.awt.SystemTray;
import java.awt.Toolkit;
import java.awt.TrayIcon;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.HashMap;
import java.util.Map;

import com.wxg.toolkit.util.ResUtils;

public class InitSysTray {

	private SystemTray systray = null;
	private Map<String, MenuItem> map4MenuItems = new HashMap<String, MenuItem>();
	
	/**
	 * 
	 */
	public void init(){
		if(SystemTray.isSupported()){
			systray = SystemTray.getSystemTray();
			try {
				addTrayIcon(systray);
			} catch (AWTException e) {
				e.printStackTrace();
			}
		}
	}
	
	/**
	 * 
	 * @param systray
	 * @throws AWTException
	 */
	private void addTrayIcon(SystemTray systray) throws AWTException{
		TrayIcon trayicon = null;
		String imgpath = ResUtils.getResourcePath("com.wxg.images.itachi_16px.png", false);
		Image img = Toolkit.getDefaultToolkit().getImage(imgpath);
		trayicon = new TrayIcon(img);
		setPopupmenu(trayicon);
		systray.add(trayicon);
		bindingMenuItemEvent();
	}
	
	/**
	 * 
	 * @param trayicon
	 */
	private void setPopupmenu(TrayIcon trayicon){
		PopupMenu popupmenu = new PopupMenu();
		MenuItem quitMenuItem = new MenuItem("Quit");
		MenuItem mainFrameMenuItem = new MenuItem("MainFrame");
		addMenuItem(popupmenu, quitMenuItem, "quit");
		addMenuItem(popupmenu, mainFrameMenuItem, "mainframe");
		trayicon.setPopupMenu(popupmenu);
	}
	
	/**
	 * 
	 * @param popupmenu
	 * @param menuitem
	 * @param menuitemKey
	 */
	private void addMenuItem(PopupMenu popupmenu, MenuItem menuitem, String menuitemKey){
		popupmenu.add(menuitem);
		map4MenuItems.put(menuitemKey, menuitem);
	}
	
	/**
	 * 
	 */
	private void bindingMenuItemEvent(){
		MenuItem quit = map4MenuItems.get("quit");
		MenuItem mainframe = map4MenuItems.get("mainframe");
		quit.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				System.out.println("quit");
				TrayIcon[] trayicons = systray.getTrayIcons();
				for(TrayIcon icon : trayicons){
					systray.remove(icon);
				}
				System.exit(0);
			}
		});
		mainframe.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				System.out.println("mainframe");
			}
		});
	}
}
